<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            list-style: none;
        }
        input{outline: none;}
        header{
            display: flex;
            height: 50px;
            background-color: blue;
            justify-content: space-between;
            align-items: center;
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
        }
        header div{
            color: white;
            font-size: 25px;
            font-weight: 700;
        }
        section{
            margin-top: 50px;
            margin-bottom: 50px;
        }
        footer{
            height: 50px;
            display: flex;
            position: fixed;
            left: 0;
            right: 0;
            bottom: 0;
            justify-content: space-between;
            background-color: blue;
        }
        footer .boxEdit{
            width: 70%;
            border-bottom: 2px solid white;
            margin-bottom: 5px;
        }
        footer .btn{
            width: 50px;
            height: 50px;
            line-height: 50px;
            font-size: 20px;
            color:#fff;

        }
        .time{
            text-align: center;
        }
                
        .text-img-left{
            display: flex;
            justify-content: flex-start;  
            /* background-color: red;           */
        }

        .text-img-right{
            display: flex;
            justify-content: flex-end;
            /* background-color: aquamarine; */
        }
        .text-img-left p{
            
            margin-right: 15px;
            padding: 3px 6px;
            border: 15px solid transparent;
            border-image: url(images/气泡3.png) 15 15 fill stretch;
        }
        .text-img-right p{
            
            margin-left: 15px;
            padding:3px 6px;
            border: 15px solid transparent;
            border-image: url(images/气泡4.png) 15 15 fill stretch;

        }
        #upload{
            width: 61px;
            height: 50px;
            background-image: url(images/head.png);
            background-repeat: no-repeat;
        }

    </style>
</head>

<body>
    <div id="wrap">
        <header>
            <div><</div>
            <div><p>聊天</p></div>
            <div>...</div>
        </header>
        <section class="list">
            
            


        </section>
        <footer>
            <input id="file" type="file" multiple hidden>
            <div id="upload"></div>
            <div class="boxEdit" contenteditable="true"></div>
            <div class="btn">发送</div>
        </footer>
    </div>
   
    <script>
        var boxEdit = document.querySelector('.boxEdit');
        var btn = document.querySelector('.btn');
        var list = document.querySelector('.list');
        var upload = document.querySelector('#upload');
        var file =document.querySelector('#file');
        var socket = new WebSocket('ws://localhost:4080');
        var timer = '';

        upload.onclick = function(){
            file.click();
        }
        //监视图片
        file.onchange = function(){
            //console.log(this.value);
            console.log(this.files);
            console.log(this.files[0]);
            var f = this.files[0];
            var fr = new FileReader();//文件读取
            fr.readAsDataURL(f);  //把fille对象读取成base64字符串
            console.log(fr.result);
            fr.onload = function(){
                 // $.ajax({  //真实案例中会需要有上传图片的接口，
                //   url: 'aasdf/aa',
                //   type: 'post',
                //   data: {
                //     files: fr.result  //前端调用接口把图片字符串传给后台，后台返回在线访问路径
                //   },
                //   success: function(res){
                //     res = 'http://aa.com/aa/a.png'
                //   }
                // })
                socket.send(JSON.stringify({
                    name:'浩',
                    msg:boxEdit.innerHTML,
                    img:fr.result,
                    time:new Date().format('yyyy-MM-dd HH:mm:ss')
                }))
            }


        }



        socket.onopen = function(){
            console.log('socktet open');          
        }
       btn.onclick = function(e){
            socket.send(JSON.stringify({
                name:'浩',
                msg:boxEdit.innerHTML,
                time:new Date().format('yyyy-MM-dd HH:mm:ss')

            }))
            boxEdit.innerHTML = '';

        }

        boxEdit.onkeydown = function(e){
            if(e.keyCode == 13){
                btn.onclick();
                return false;
            }
        }
        socket.onmessage = function(e){
            console.log(e.data);
            var user = '雪'
            var data = JSON.parse(e.data);
            var p = document.createElement('p');
            if(data.name == user){
                if(data.img){
                    console.log(data.img);
                    p.innerHTML = `<div class="item">`;

                    if(timer == '' || new Date().getTime() - new Date(timer).getTime() >= 6000 ){
                        p.innerHTML += `<div class="time">${data.time}</div>`;
                        
                    }                    
                    p.innerHTML += `    <div class="text-img-right">
                                            <p><span>${data.msg}</span><img src=${data.img}></p>
                                            <figure><img src="images/head.png" alt=""></figure>
                                        </div>
                                    </div>`

                }else{
                    p.innerHTML = `<div class="item">`;

                    if(timer == '' || new Date().getTime() - new Date(timer).getTime() >= 6000 ){
                        p.innerHTML += `<div class="time">${data.time}</div>`;
                        
                    }                    
                    p.innerHTML += `    <div class="text-img-right">
                                            <p><span>${data.msg}</span></p>
                                            <figure><img src="images/head.png" alt=""></figure>
                                        </div>
                                    </div>`
                }                
            }else{
                if(data.img){
                    p.innerHTML = `<div class="item">`;

                        if(timer == '' || new Date().getTime() - new Date(timer).getTime() >= 6000 ){
                            p.innerHTML += `<div class="time">${data.time}</div>`;
                            
                        }                    
                        p.innerHTML += `    <div class="text-img-left">
                                                <figure><img src="images/head.png" alt=""></figure>
                                                <p><span>${data.msg}</span><img src=${data.img}></p>
                                            </div>
                                        </div>`

                }else{
                    p.innerHTML = `<div class="item">`;

                    if(timer == '' || new Date().getTime() - new Date(timer).getTime() >= 6000 ){
                        p.innerHTML += `<div class="time">${data.time}</div>`;
                        
                    }                    
                    p.innerHTML += `    <div class="text-img-left">
                                           <figure><img src="images/head.png" alt=""></figure>
                                            <p><span>${data.msg}</span></p>
                                        </div>
                                    </div>`
                }                

            }
            
            list.append(p);
            
            timer = data.time;
           // console.log(timer);
           // console.log(new Date(timer).getTime());
           
            

          



            //让滚动条到最底部
            var html = document.querySelector('html');
            html.scrollTop = html.offsetHeight;
            
           

        }
        socket.onclose = function(event){
            console.log('close');
        }


        Date.prototype.format = function (fmt) { 
			var o = {
				"M+": this.getMonth() + 1, //月份 
				"d+": this.getDate(), //日 
				"H+": this.getHours(), //小时 
				"h+": this.getHours() > 12 ? this.getHours() -12 : this.getHours(), //小时 
				"m+": this.getMinutes(), //分 
				"s+": this.getSeconds(), //秒 
				"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
				"S": this.getMilliseconds() //毫秒 
			};
			if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
			for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			return fmt;
		}
    </script>

</body>

</html>